package com.zxy.supplier_system.server.entity

import jakarta.persistence.*
import org.hibernate.annotations.DynamicInsert
import org.hibernate.annotations.DynamicUpdate
import org.springframework.data.jpa.domain.support.AuditingEntityListener
import java.io.Serializable

@Entity
@DynamicUpdate
@DynamicInsert
@Table(
    uniqueConstraints = [
        UniqueConstraint(
            name = "market_order_item_market_order_id_goods_id_sub_goods_id_uindex",
            columnNames = ["market_order_id", "goods_id","sub_goods_id"]
        )
    ]
)
class MarketDeliveryOrderItem {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    var id: Int?=null

    @ManyToOne(optional = false)
    @JoinColumn
    lateinit var goods: Goods

    @ManyToOne
    @JoinColumn
    var subGoods:SubGoods? = null

    @Column(nullable = false)
    var amount: Int = 0

    @ManyToOne(optional = false)
    @JoinColumn(nullable = false)
    lateinit var order:MarketDeliveryOrder

    var sequence:Int = 0

    @ManyToOne( cascade = [CascadeType.ALL])
    @JoinColumn
    var unit:GoodsUnit? = null

    @get:Transient
    val amountWithUnit: Int
        get() = if (unit == null) amount else amount * unit!!.basicMultiple

}

val List<MarketDeliveryOrderItem>.nextSequence:Int
    get() = this.maxOfOrNull { it.sequence }?.plus(1)?:0
